package com.rzico.sbl.ui.report.manager

import android.os.Bundle
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.github.mikephil.extend.setChartValueSelectedListener
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportManagerBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.model.ManagerGoodsData
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.viewmodel.ReportManagerViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseRootActivity
import com.xinnuo.common_ui.base.addItems
import org.json.JSONObject

class ReportManagerActivity : BaseRootActivity() {

    private lateinit var mBinding: ActivityReportManagerBinding

    private var mAreaName = ""

    // 销量统计
    private val mAreaList = ArrayList<ManagerGoodsData>()
    private var mSaleBeginDate = getBeforeDate(6)
    private var mSaleEndDate = getTodayDate()

    // 订单
    private var mOrderBeginDate = getBeforeDate(6)
    private var mOrderEndDate = getTodayDate()

    // 商品
    private val mGoodsList = ArrayList<ManagerGoodsData>()
    private val mRangeList = ArrayList<ManagerDate>()
    private var mProductSn = ""
    private var mGoodsBeginDate = getBeforeDate(6)
    private var mGoodsEndDate = getTodayDate()

    override fun getViewModel() = get<ReportManagerViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityReportManagerBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        transparentStatusBar()

        initData()
        initListener()

        getData()
    }

    override fun initData() {
        mBinding.also {
            it.managerSale.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mAreaList[0].data.indices) ""
                    else
                        mAreaList[0].data[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.managerOrder.initChart()

            it.managerGoods1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    xTextSize = 8f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mGoodsList.indices) ""
                    else mGoodsList[value.toInt()].name
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductSn = mGoodsList[index].sn
                        mBinding.managerGoodsTitle.text = mGoodsList[index].name
                        getRangeData()
                    }
                }
            }

            it.managerGoods2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mRangeList.indices) ""
                    else mRangeList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            managerSaleTime.addTimeListener { start, end, _ ->
                mSaleBeginDate = start
                mSaleEndDate = end

                getViewModel().cancelRequest()
                getData()
            }

            managerOrderTime.addTimeListener { start, end, _ ->
                mOrderBeginDate = start
                mOrderEndDate = end

                getViewModel().cancelRequest()
                getOrderData()
            }

            managerGoodsTime.addTimeListener { start, end, _ ->
                mGoodsBeginDate = start
                mGoodsEndDate = end

                getViewModel().cancelRequest()
                getBrandData()
            }
        }
    }

    /**
     * TabLayout 初始化
     */
    private fun initTabLayout() {
        mBinding
            .managerTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mAreaName = when (it.position) {
                                0 -> ""
                                else -> mAreaList[it.position - 1].name
                            }

                            getViewModel().cancelRequest()
                            getOrderData()
                            getBrandData()
                        }
                    }
                }

                // 移除所有Tab
                removeAllTabs()

                addTab(this.newTab().setText("全部"), true)
                mAreaList.forEach {
                    addTab(this.newTab().setText(it.name), false)
                }
            }
    }

    /**
     * 设置销量统计数据
     */
    private fun setTotalChart() {
        mAreaList.sumOf { item ->
            item.data.sumOf {
                it.quantity.intValue
            }
        }.apply {
            mBinding
                .managerSaleTotal
                .text = if (this > 0) " (总: ${this})" else ""
        }

        mBinding
            .managerSale
            .apply {
                if (mAreaList.isEmpty()
                    || mAreaList.none { item ->
                        item.data.sumOf { it.quantity.intValue } > 0
                    }
                ) clear()
                else {
                    setGroupData(
                        entries = mAreaList.map {
                            it.data.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.quantity.toFloat())
                            }
                        },
                        colorList = getViewModel().color3(),
                        labelList = mAreaList.map {
                            "${it.name}水站${it.quantity}个"
                        },
                        xFromValue = 0f
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置饼状图数据
     */
    private fun setChartData(
        total: Int,
        amountArray: Array<Int>
    ) {
        mBinding
            .managerOrder
            .apply {
                if (total == 0) clear()
                else {
                    formartCenterText(
                        value = total.toString(),
                        hint = "订单总数",
                        valueColor = R.color.colorAccent
                    )

                    setPieData(
                        colors = getViewModel().orderColor(),
                        formatter = CustomValueFormatter(),
                        PieEntry(amountArray[0].toFloat(), "待接单"),
                        PieEntry(amountArray[1].toFloat(), "配送中"),
                        PieEntry(amountArray[2].toFloat(), "已完成")
                    )
                }

                animateY(1000, Easing.EaseInOutQuad)
            }
    }

    /**
     * 设置所有商品销量柱状图数据
     */
    private fun setBrandData() {
        mGoodsList.sumOf {
            it.quantity.intValue
        }.apply {
            mBinding
                .managerGoodsTotal
                .text = if (this > 0) " (总: ${this})" else ""
        }

        mBinding
            .managerGoods1
            .apply {
                if (mGoodsList.isEmpty()) {
                    clear()
                    mBinding.managerGoods2.clear()
                    mBinding.managerGoodsTitle.text = "暂无商品"
                } else {
                    setSingleData(
                        entries = mGoodsList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity.toFloat())
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置单个商品销量柱状图数据
     */
    private fun setGoodsData() {
        mBinding
            .managerGoods2
            .apply {
                setSingleData(
                    entries = mRangeList.mapIndexed { index, data ->
                        BarEntry(index.toFloat(), data.quantity.toFloat())
                    },
                    colorList = listOf(
                        getViewModel()
                            .brandColor()[
                                mGoodsList.indexOfFirst { it.sn == mProductSn } % 24
                        ]
                    ),
                    isHighlight = false,
                    formatter = CustomValueFormatter()
                )

                animateY(500)
            }
    }

    /**
     * 获取销量统计数据
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .areaList(
                beginDate = mSaleBeginDate,
                endDate = mSaleEndDate,
                isLoading = true,
                onSuccess = {
                    mAreaList.clear()
                    mAreaList.addItems(it)

                    if (mBinding.managerTab.tabCount == 0) initTabLayout()

                    setTotalChart()
                }
            )
    }

    /**
     * 获取订单饼状图数据
     */
    private fun getOrderData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zOrderSum,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "area" to mAreaName,
                    "beginDate" to mOrderBeginDate,
                    "endDate" to mOrderEndDate
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    arrayOf(
                        obj.optNotNull("unconfirmed").intValue,
                        obj.optNotNull("confirmed").intValue,
                        obj.optNotNull("completed").intValue
                    ).apply {
                        setChartData(sum(), this)
                    }
                }
            )
    }

    /**
     * 获取所有商品销量
     */
    private fun getBrandData() {
        getViewModel()
            .goodsBrandList(
                area = mAreaName,
                beginDate = mGoodsBeginDate,
                endDate = mGoodsEndDate,
                onSuccess = { list ->
                    mGoodsList.clear()
                    mGoodsList.addItems(list)

                    setBrandData()

                    if (mGoodsList.isNotEmpty()) {
                        if (mGoodsList.none { it.sn == mProductSn }) {
                            mProductSn = mGoodsList[0].sn
                            mBinding.managerGoodsTitle.text = mGoodsList[0].name
                        }
                        getRangeData()
                    }
                }
            )
    }

    /**
     * 获取单个商品最近销量
     */
    private fun getRangeData() {
        getViewModel()
            .goodsSaleList(
                goodsSn = mProductSn,
                area = mAreaName,
                beginDate = mGoodsBeginDate,
                endDate = mGoodsEndDate,
                onSuccess = {
                    mRangeList.clear()
                    mRangeList.addItems(it)

                    setGoodsData()
                }
            )
    }

}